﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data.Objects;
using Relocation.Com.Tools;
using System.Linq;
using System.Data.Objects.DataClasses;
using Relocation.Com;



namespace Relocation.Base.UI
{
	/// <summary>
	/// 所有列表窗父类,提供通用的控件布局属性,并继承自BaseList
	/// </summary>
	/// <typeparam name="TEntity"></typeparam>
	public abstract partial class BaseFormList<TEntity> : BaseForm
	where TEntity : System.Data.Objects.DataClasses.EntityObject
	{
		public BaseFormList()
			: base()
		{
			InitializeComponent();
		}

		public BaseFormList(Session session) :
			base(session)
		{
			InitializeComponent();
		}

		/// <summary>
		/// 初始化控件
		/// </summary>
		private void Initialize()
		{
			initControls(this.Controls);
			initBindingSource();
		}



		protected ObjectQuery<TEntity> _ObjectQuerySearch;
		/// <summary>
		/// 带搜索条件的ObjectQuery（查询之后的对象）
		/// </summary>
		public ObjectQuery<TEntity> ObjectQuerySearch
		{
			get
			{
				return this._ObjectQuerySearch == null ? this.ObjectQuery : _ObjectQuerySearch;
			}
			set
			{
				this._ObjectQuerySearch = value;
			}
		}

		/// <summary>
		/// 当前页面的结果集合
		/// </summary>
		public ObjectQuery<TEntity> ObjectQuery
		{
			get;
			set;
		}

		public void Sort(DataGridViewColumn dataGridViewColumn)
		{
			this.sort(dataGridViewColumn, this.ObjectQuery, this.BindingSource);
		}

		#region 删除方法

		/// <summary>
		/// 自动删除用户选中的记录
		/// </summary>
		public void DeleteEntity()
		{
			try
			{
				TEntity entity = this.GetSelectEntity();
				this.DeleteEntity(entity);
			} catch (Exception ex)
			{
				this.Log.Error(ex);
				MyMessagebox.Error("记录删除失败！");
			}
		}

		private DataGridView _DataGridView = null;

		/// <summary>
		/// 返回当前窗体中的DataGridView
		/// </summary>
		/// <returns></returns>
		public virtual DataGridView GetDataGridView()
		{
			if (_DataGridView == null)
				_DataGridView = FindSingleControl<DataGridView>(this.Controls);
			return _DataGridView;
		}


		/// <summary>
		/// 在控件集合中递归查找控件（第一个）
		/// </summary>
		/// <typeparam name="ControlType">控件的类型</typeparam>
		/// <param name="controls">控件集合</param>
		/// <returns>找到的控件</returns>
		public ControlType FindSingleControl<ControlType>(Control.ControlCollection controls)
			where ControlType : Control
		{
			if (controls == null)
				return null;
			ControlType tempControl = null;
			foreach (Control control in controls)
			{
				if (control is ControlType)
					return control as ControlType;
				else
				{
					if (control.HasChildren)
					{
						tempControl = FindSingleControl<ControlType>(control.Controls);
						if (tempControl != null)
							return tempControl;
					}
				}
			}
			return null;
		}



		#region 在GridView中选中实体
		/// <summary>
		/// 在GridView中选中实体
		/// </summary>
		/// <param name="entity">指定实体</param>
		public void SelectEntity(TEntity entity)
		{
			SelectEntity(entity, null);
		}

		/// <summary>
		/// 在GridView中选中实体
		/// </summary>
		/// <param name="entity">指定实体</param>
		/// <param name="compareHandler">比较实体是否相等的委托</param>
		public void SelectEntity(TEntity entity, CompareHandler compareHandler)
		{
			if (entity == null)
				return;
			DataGridView dataGridView = GetDataGridView();
			if (dataGridView == null)
				return;
			dataGridView.ClearSelection();
			TEntity tempEntity;
			foreach (DataGridViewRow row in dataGridView.Rows)
			{
				tempEntity = row.DataBoundItem as TEntity;
				if (tempEntity == null)
					continue;
				if (compareHandler != null ? compareHandler(entity, tempEntity) : entity.Equals(tempEntity))
				{
					row.Selected = true;
					break;
				}
			}
		}
		#endregion



		/// <summary>
		/// 比较两个实体是否相同
		/// </summary>		
		public delegate bool CompareHandler(EntityObject tagEntity, EntityObject rowEntity);

		/// <summary>
		/// 默认排序字段排序字段
		/// </summary>
		public string SortField
		{
			get;
			set;
		}

		/// <summary>
		/// 排序方式
		/// </summary>
		private ListSortDirection _SortDirection = ListSortDirection.Descending;

		/// <summary>
		/// 排序方式，默认为Descending（凡排序）
		/// </summary>
		public ListSortDirection SortDirection
		{
			get
			{
				return _SortDirection;
			}
			set
			{
				_SortDirection = value;
			}
		}


		/// <summary>
		/// 删除实体（有弹出框提示）
		/// </summary>
		/// <param name="tagEntity"></param>
		protected virtual void DeleteEntity(TEntity entity)
		{
			try
			{
				if (entity == null)
					return;
				DialogResult result = MyMessagebox.Confirm("您确定要删除该条记录吗？");
				if (result.Equals(DialogResult.Yes))
				{
					this.Session.DataModel.Delete(entity as TEntity);
				}
			} catch (Exception ex)
			{
				this.Log.Error(ex);
				MyMessagebox.Error("记录删除失败！");
			}
			this.Reload();
		}
		#endregion


		/// <summary>
		/// 递归遍历所有控件，用于同意设置属性
		/// </summary>
		/// <param name="controls"></param>
		protected void initControls(Control.ControlCollection controls)
		{
			foreach (Control control in controls)
			{
				if (control is DataGridView)
				{
					initDataGridView(control as DataGridView);
					break;
				}
				if (control.Controls.Count > 0)
					initControls(control.Controls);
			}
		}

		/// <summary>
		/// 初始化列表页面的DataGridView（设置属性、绑定事件）
		/// </summary>
		/// <param name="dataGridView"></param>
		private void initDataGridView(DataGridView dataGridView)
		{
			//设置属性
			dataGridView.AllowUserToAddRows = false;
			dataGridView.AllowUserToDeleteRows = false;
			dataGridView.AllowUserToOrderColumns = true;
			dataGridView.AllowUserToResizeRows = false;
			DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
			dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
			dataGridView.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
			dataGridView.AutoGenerateColumns = false;

			try
			{
				dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
			} catch (Exception)
			{

			}
			//dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;

			dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
			dataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
			//dataGridView.Location = new System.Drawing.Point(0, 0);
			dataGridView.MultiSelect = false;
			dataGridView.ReadOnly = true;
			dataGridView.RowHeadersVisible = false;
			dataGridView.RowTemplate.Height = 23;
			dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
			//dataGridView.Size = new System.Drawing.Size(960, 511);
			dataGridView.TabIndex = 0;

			//绑定排序的事件
			dataGridView.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(delegate(object sender, DataGridViewCellMouseEventArgs e) {
				DataGridViewColumn column = dataGridView.Columns[e.ColumnIndex];
				if (column == null || String.IsNullOrEmpty(column.DataPropertyName))
					return;
				sort(column, this.ObjectQuerySearch, this.BindingSource);
			});
			dataGridView.DataError += new DataGridViewDataErrorEventHandler(DataGridViewDataError);
			dataGridView.CellDoubleClick += new DataGridViewCellEventHandler(DataGridView_CellDoubleClick);
			dataGridView.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(CellToolTipTextNeeded);
		}

		/// <summary>
		/// 处理DataError 事件
		/// </summary>		
		protected virtual void DataGridViewDataError(object obj, DataGridViewDataErrorEventArgs e)
		{
			this.Log.Error(e.Exception);
		}

		protected virtual void DataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0)
				return;
			this.ButtonEdit.PerformClick();
		}

		protected virtual void CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
		{
			try
			{
				if (e.RowIndex >= 0)
				{
					DataGridView dataGridView = sender as DataGridView;
					
					if (dataGridView != null)
					{
						object dataBouneItem = dataGridView.Rows[e.RowIndex].DataBoundItem;
						if (dataBouneItem != null)
						{
							TEntity entity = dataGridView.Rows[e.RowIndex].DataBoundItem as TEntity;
							string toolTipText =this.Entity2ToolTipText(entity);
							e.ToolTipText = toolTipText;
						}
					}					
				}
			} catch (Exception ex)
			{
				Log.Error(ex);
			}
		}

		/// <summary>
		/// 返回实体对象的ToolTipText信息，需子类重写
		/// </summary>		
		protected virtual string Entity2ToolTipText(TEntity entity, string remarkName = "remark")
		{
			try
			{
				System.Reflection.PropertyInfo pinfo = typeof(TEntity).GetProperty(remarkName);
				if (pinfo == null)
					return string.Empty;
				string value = (string)pinfo.GetValue(entity, null);
				return string.IsNullOrEmpty(value) ? string.Empty : ("备注：" + value);
			} catch (Exception ex)
			{				
				Log.Error(ex);
				System.Diagnostics.Debug.WriteLine(ex);
				return string.Empty;
			}

		}



		private void initBindingSource()
		{
			this.BindingSource.DataSourceChanged += new EventHandler(delegate(object sender, EventArgs e) {
				this.BindingSource.MoveFirst();
			});
		}



		private void BaseListForm_Load(object sender, EventArgs e)
		{

			if (this.Session == null && !this.DesignMode)
				throw new Exception("Session没有实例化");

			Initialize();

			if (string.IsNullOrEmpty(this.SortField))
			{
				this.SetDataSource(this.ObjectQuerySearch == null ? null : this.ObjectQuerySearch.ToList());
			} else
			{
				this.SetDataSource(this.Session.DataModel.sort(this.ObjectQuerySearch, this.SortField, this.SortDirection).ToList());
			} 

		
		}

		private void ButtonSearch_Click(object sender, EventArgs e)
		{
			if (this.ObjectQuerySearch == null)
				throw new Exception("this.ObjectSet未初始化！");
			String queryString = this.GetSearchString();
			this.ObjectQuerySearch = String.IsNullOrEmpty(queryString) ? this.ObjectQuery : this.ObjectQuery.Where(queryString);
			this.SetDataSource(this.Session.DataModel.sort(this.ObjectQuerySearch, this.SortField, this.SortDirection).ToList());
		}



		/// <summary>
		/// 刷新按钮（清空搜索条件，显示全部）
		/// </summary>		
		private void ButtonRefresh_Click(object sender, EventArgs e)
		{
			this.ButtonClear_Click(null, null);
			this.ButtonSearch_Click(null, null);
		}

		/// <summary>
		/// 清空搜索条件		
		/// </summary>		
		private void ButtonClear_Click(object sender, EventArgs e)
		{
			this.ResetSearchControls();
		}

		/// <summary>
		/// 返回当前列表选中的实体对象
		/// </summary>
		/// <returns></returns>
		public virtual TEntity GetSelectEntity()
		{
			return this.BindingSource.Current as TEntity;
		}

		/// <summary>
		/// 刷新当前列表数据
		/// </summary>
		public void Reload()
		{
			try
			{
				if (this.ObjectQuerySearch == null)
					throw new Exception("this.ObjectSet未初始化");
				if (string.IsNullOrEmpty(this.SortField))
				{
					SetDataSource(this.ObjectQuerySearch.ToList());
				}
				else
				{
					SetDataSource(this.Session.DataModel.sort(this.ObjectQuerySearch, this.SortField, this.SortDirection).ToList());
				}
			}
			catch (Exception ex)
			{				
				Log.Error(ex);
				throw;
			}

		}

		/// <summary>
		/// 刷新当前数据
		/// </summary>
		public void Reload(String sortField)
		{
			SetDataSource(this.Session.DataModel.sort(this.ObjectQuerySearch, sortField, ListSortDirection.Descending).ToList());
		}

		private void SetDataSource(List<TEntity> source)
		{
			this.BindingSource.DataSource = this.DataSourceRander == null ? source : this.DataSourceRander(source);
		}


		public DataSourceRanderHandel DataSourceRander
		{
			get;
			set;
		}
		public delegate object DataSourceRanderHandel(List<TEntity> source);


		/// <summary>
		/// 排序
		/// </summary>
		/// <typeparam name="TEntity">实体类型</typeparam>
		/// <param name="column">DataGridViewColumn </param>        
		/// <param name="objectQuery">数据查询对象</param>
		/// <returns>排序后的查询对象</returns>
		public ObjectQuery<TEntity> sort(DataGridViewColumn column, ObjectQuery<TEntity> objectQuery, BindingSource bindingSource)
		{
			if (column == null || String.IsNullOrEmpty(column.DataPropertyName))
				return objectQuery;
			ListSortDirection direction = column.HeaderCell.SortGlyphDirection.Equals(SortOrder.Descending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
			objectQuery = this.Session.DataModel.sort(objectQuery, column.DataPropertyName, direction);
			this.SetDataSource(objectQuery.ToList());
			if (!column.SortMode.Equals(DataGridViewColumnSortMode.NotSortable))
				column.HeaderCell.SortGlyphDirection = direction.Equals(ListSortDirection.Ascending) ? SortOrder.Ascending : SortOrder.Descending;
			return objectQuery;
		}

		private void ButtonDel_Click(object sender, EventArgs e)
		{

		}

		/// <summary>
		/// 返回修改按钮
		/// </summary>
		/// <returns></returns>
		public Button GetEditButton()
		{
			return this.ButtonEdit;
		}
	
	}
}
